package com.ruoyi.crm.Listener;

import com.dingtalk.api.request.OapiMessageCorpconversationAsyncsendV2Request;
import com.ruoyi.common.config.DDConstant;
import com.ruoyi.common.enums.flow.FlowTypeEnum;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.dd.MessageUtil;
import com.ruoyi.common.utils.flow.FlowDTO;
import com.ruoyi.crm.domain.CrmContract;
import com.ruoyi.crm.domain.CrmOrder;
import com.ruoyi.crm.domain.CrmTask;
import com.ruoyi.crm.mapper.CrmOrderMapper;
import com.ruoyi.crm.mapper.CrmTaskMapper;
import com.ruoyi.crm.strategy.CrmOrderContext;
import com.ruoyi.crm.strategy.CrmOrderFlowStrategy;
import com.taobao.api.ApiException;
import com.warm.flow.core.constant.ExceptionCons;
import com.warm.flow.core.entity.Instance;
import com.warm.flow.core.listener.Listener;
import com.warm.flow.core.listener.ListenerVariable;
import com.warm.flow.core.utils.AssertUtil;
import com.warm.tools.utils.ArrayUtil;
import com.warm.tools.utils.CollUtil;
import com.warm.tools.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Iterator;
import java.util.Map;

/**
 * 工单流程启动监听器
 *
 * @author 陈彬彬
 * @date 2023-04-11
 */
@Component
@Slf4j
public class CrmTaskListener implements Listener {

    @Resource
    private CrmOrderMapper crmOrderMapper;
    @Resource
    private CrmTaskMapper crmTaskMapper;

    @Autowired
    private CrmOrderContext crmOrderContext;

    /**
     * 流程启动修改 设置项目负责人代办人
     *
     * @author 陈彬彬
     * @date 2023-04-11
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void notify(ListenerVariable variable) {
        log.error("开始监听器;{}", variable);
        /**
         * 修改flowNode表的
         */
         //获取流程定义id
        Instance instance = variable.getInstance();
        //流程定义id  目前写死的 1315000019476156416(表单id) 和节点名称 项目负责人
        String businessId = instance.getBusinessId();
        //根据业务id获取工单对象
        CrmTask crmTask = crmTaskMapper.selectById(businessId);
        String orderId = crmTask.getOrderId();
        //获取商机
        CrmOrder crmOrder = crmOrderMapper.selectById(orderId);
        //商机所属人id
        String userId = crmOrder.getUserId();
        //权限标识 admin默认有权限
        String permissionFlag =  "user:" + userId + ",role:1";
        String hisTaskTableName = "flow_his_task";
        String taskTableName = "flow_task";
//        String nodeTableName = "flow_node";
//        crmTaskMapper.setDynamicAgent("1315000019476156416","项目负责人",permissionFlag,nodeTableName);
        crmTaskMapper.setDynamicAgent("1315000019476156416","项目负责人",permissionFlag,taskTableName, crmTask.getId());
        crmTaskMapper.setDynamicAgent("1315000019476156416","项目负责人",permissionFlag,hisTaskTableName, crmTask.getId());

        OapiMessageCorpconversationAsyncsendV2Request.Msg msg = new OapiMessageCorpconversationAsyncsendV2Request.Msg();
        msg.setMsgtype("markdown");
        msg.setMarkdown(new OapiMessageCorpconversationAsyncsendV2Request.Markdown());
        msg.getMarkdown().setTitle("工单审批提醒");
        String text = this.builder(instance);
        msg.getMarkdown().setText(text.toString());
        //发送钉钉 工作通知
        try {
            MessageUtil.send(userId, msg);
        } catch (ApiException e) {
            throw new RuntimeException(e);
        }
    }


    private String builder(Instance instance){
        Long definitionId = instance.getDefinitionId();
        String businessId = instance.getBusinessId();
        String name = FlowTypeEnum.getNameByDefinitionId(definitionId.toString());
        CrmOrderFlowStrategy orderFlowService = crmOrderContext.getOrderFlowService(name);
        FlowDTO flowDTO = orderFlowService.conversionObjByLocal(businessId);

        StringBuilder text = new StringBuilder();
        text.append("## " + flowDTO.getSubmitUser() + "提交的工单申请，请审批！");
        text.append("  \n  ");
        Map<String, Object> businessValue = flowDTO.getBusinessValue();
        Iterator<Map.Entry<String, Object>> iterator = businessValue.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, Object> entry = iterator.next();
            text.append(entry.getKey() + ": " + entry.getValue());
            text.append("  \n  ");
        }

        text.append("  \n  ");
        text.append("[立即查看](" + DDConstant.DD_FRONT_URL + DDConstant.FRONT_URL_HOST + "flow/todo)");
        return text.toString();
    }
}
